<template>
    <div class="app-container">

        <!-- 查询和其他操作 -->
        <div class="filter-container">
            <!--非等值查询条件示例 <el-input v-model="queryorther.label" clearable class="filter-item" style="width: 150px;"
                            placeholder="请输入源标签"/>-->
            <!--      <el-cascader :options="dictOptions" :props="{ value: 'dictName',label: 'dictName'}"-->
            <!--                   ref="owner"  :placeholder="listQuery.category" @change="getOwner" :show-all-levels="false" />-->
            <#if columnBeanList?exists>
                <#list columnBeanList as model>
                    <el-input v-model="listQuery.${model.attrname}" clearable class="filter-item" style="width: 150px;"
                              placeholder="请输入${model.comments!}"/>
                </#list>
            </#if>
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search"
                       @click="handleFilter">搜索
            </el-button>
            <el-button class="filter-item"  type="primary" icon="el-icon-edit"
                       @click="handleCreate">新增
            </el-button>
            <el-button class="filter-item" type="primary" icon="el-icon-delete"
                     @click="revomveAll" :disabled="selectedIds.length === 0" >批量删除</el-button>
            <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
                       @click="">导出
            </el-button>
        </div>

        <!-- 查询结果 -->
        <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row
                  @selection-change="handleSelectionChange"  @sort-change="sortChange">
            <!--排序切换示例 <el-table-column prop="url" show-overflow-tooltip sortable="custom"/>  -->
            <el-table-column type="selection" label="序号"/>
            <#if columnBeanList?exists>
                <#list columnBeanList as model>
                    <el-table-column align="center" label="${model.comments!}" prop="${model.attrname}"/>
                </#list>
            </#if>
            <el-table-column align="center" label="操作" class-name="small-padding fixed-width" fixed="right" min-width="180">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">编辑
                    </el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                    @pagination="getList"/>

        <!-- 添加或修改对话框 -->
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left"
                     label-width="100px" style="width: 400px; margin-left:50px;">
                <#if columnBeanList?exists>
                    <#list columnBeanList as model>
                        <el-form-item label="${model.comments!}" prop="${model.attrname}">
                            <el-input v-model="dataForm.${model.attrname}"/>
                        </el-form-item>
                    </#list>
                </#if>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
                <el-button v-else type="primary" @click="updateData">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import Pagination from '@/components/Pagination'
    import {
        get${poName}Info,
        get${poName}Page,
        get${poName}List,
        create${poName},
        edit${poName},
        del${poName},
        del${poName}Batch
    } from '@/api/${classNameSub}'

    export default {
        name: '${classNameSub}',
        components: {Pagination},
        data() {
            return {
              listLoading: true,
              downloadLoading: false,
              selectedIds: [],
              dictOptions: [],
              list: null,
              total: 0,
              listQuery: {
                page: 1,
                limit: 20,
                <#if columnBeanList?exists>
                <#list columnBeanList as model>
                ${model.attrname}: undefined,
                </#list>
                </#if>
                queryConditions: [],
                querySorts: [ {'alias': 'id', 'sortType': 0 } ]
              },
                queryorther: {  // 非等值查询条件
                    <#if columnBeanList?exists>
                    <#list columnBeanList as model>
                    ${model.attrname}: undefined,
                    </#list>
                    </#if>
                    searchText: undefined
                },
              dataForm: {
                <#if columnBeanList?exists>
                <#list columnBeanList as model>
                ${model.attrname}: undefined,
                </#list>
                </#if>
              },
              dialogFormVisible: false,
              dialogStatus: '',
              textMap: {
                update: '编辑',
                create: '创建'
              },
              rules: {
                <#if columnBeanList?exists>
                <#list columnBeanList as model>
                ${model.attrname}: [ { required: true, message: '${model.comments!}必填', trigger: 'change' } ],
                </#list>
                </#if>
              }
            }
        },
        created() {
            this.getList()
            this.getDictTree()
        },
        methods: {
            getDictTree() {
                this.listLoading = true
                const dictQuery = { 'parentId': null }
                getListTree(dictQuery)
                    .then(response => {
                        this.dictOptions = response.data
                        this.listLoading = false
                    })
                    .catch(() => {
                        this.dictOptions = []
                        this.listLoading = false
                    })
            },
            getList() {
                this.listLoading = true
                get${poName}Page(this.listQuery)
                    .then(response => {
                        this.list = response.data.records
                        this.total = response.data.total
                        this.listLoading = false
                    })
                    .catch(() => {
                        this.list = []
                        this.total = 0
                        this.listLoading = false
                    })
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getQueryConditions()
                this.getList()
            },
            resetForm() {
                this.dataForm = {
                  <#if columnBeanList?exists>
                  <#list columnBeanList as model>
                    ${model.attrname}: undefined,
                  </#list>
                  </#if>
                }
            },
            handleCreate() {
                this.resetForm()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            createData() {
                this.$refs['dataForm'].validate(valid => {
                    if (valid) {
                      create${poName}(this.dataForm)
                            .then(response => {
                                this.list.unshift(response.data)
                                this.dialogFormVisible = false
                                this.$notify.success({
                                    title: '成功',
                                    message: '添加成功'
                                })
                                this.getList()
                            })
                            .catch(response => {
                                this.$notify.error({
                                    title: '失败',
                                    message: response.data.errmsg
                                })
                            })
                    }
                })
            },
            handleUpdate(row) {
                this.dataForm = Object.assign({}, row)
                this.dialogStatus = 'update'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            updateData() {
                this.$refs['dataForm'].validate(valid => {
                    if (valid) {
                        edit${poName}(this.dataForm)
                            .then(() => {
                                for (const v of this.list) {
                                    if (v.id === this.dataForm.id) {
                                        const index = this.list.indexOf(v)
                                        this.list.splice(index, 1, this.dataForm)
                                        break
                                    }
                                }
                                this.dialogFormVisible = false
                                this.$notify.success({
                                    title: '成功',
                                    message: '更新成功'
                                })
                            })
                            .catch(response => {
                                this.$notify.error({
                                    title: '失败',
                                    message: response.data.errmsg
                                })
                            })
                    }
                })
            },
            handleDelete(row) {
                this.$confirm('确定删除?').then(
                    () => {
                        del${poName}(row.id)
                            .then(response => {
                                this.$notify.success({
                                    title: '成功',
                                    message: '删除成功'
                                })
                                this.getList()
                            })
                            .catch(response => {
                                this.$notify.error({
                                    title: '失败',
                                    message: response.data.errmsg
                                })
                            })
                    }
                ).catch(() => {
                    this.$message.info('取消删除')
                })
            },
            //  这里的selection是你所有选择的项
            handleSelectionChange(selection) {
                this.selectedIds = selection.map((item) => '' + item.id)
                // console.log(selection)
            },
            revomveAll() {
                this.$confirm('确定删除?')
                    .then(() => {
                        del${poName}Batch(this.selectedIds)
                            .then(response => {
                                this.$notify.success({
                                    title: '成功',
                                    message: '删除成功'
                                })
                                this.getList()
                            })
                            .catch(response => {
                                this.$notify.error({
                                    title: '失败',
                                    message: response.data.errmsg
                                })
                            })
                    })
                    .catch(() => {
                        this.$message.info('取消删除');
                    });
            },
            sortChange() {
                if ( !this.listQuery.querySorts){
                    return
                }
                for (let bean of this.listQuery.querySorts) {
                  //  alert(JSON.stringify(bean))
                    if (0 === bean.sortType) {
                        bean.sortType = 1
                    } else {
                        bean.sortType = 0
                    }
                }
                this.handleFilter()
            },
            getQueryConditions() {
                if (this.listQuery.queryConditions) {
                    this.listQuery.queryConditions.length = 0
                }
                const temp = []
                for (const key in this.queryorther) {
                    if (this.queryorther.hasOwnProperty(key)) {
                        if (key) {
                            if (this.queryorther[key]) {
                                temp.push({ 'columnName': key, 'operator': 8, 'value': this.queryorther[key] })
                            }
                        }
                    }
                }
                this.listQuery.queryConditions = temp
                // alert(JSON.stringify(this.listQuery.queryConditions))
            },
            handleDownload() {
                this.downloadLoading = true
                import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
                    const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
                    const data = this.formatJson(filterVal)
                    excel.export_json_to_excel({
                        header: tHeader,
                        data,
                        filename: 'table-list'
                    })
                    this.downloadLoading = false
                })
            },
            formatJson(filterVal) {
                return this.list.map(v => filterVal.map(j => {
                    if (j === 'timestamp') {
                        return parseTime(v[j])
                    } else {
                        return v[j]
                    }
                }))
            },
            getOwner(node) {
                if (this.$refs.owner.checkedValue.length === 0) {
                    this.listQuery.category = undefined
                }
                const tempObj = this.$refs.owner.getCheckedNodes()[0]
                this.listQuery.category = tempObj.label
            }
        }
    }
</script>
